package com.heart.sell.service.impl;

import com.heart.sell.converter.OrderMaster2OrderDTOConverter;
import com.heart.sell.dao.OrderDetailMapper;
import com.heart.sell.dao.OrderMasterMapper;
import com.heart.sell.dto.CartDTO;
import com.heart.sell.dto.OrderDTO;
import com.heart.sell.enums.OrderStatusEnum;
import com.heart.sell.enums.PayStatusEnum;
import com.heart.sell.enums.ResponseCodeEnum;
import com.heart.sell.exception.SellException;
import com.heart.sell.pojo.OrderDetail;
import com.heart.sell.pojo.OrderMaster;
import com.heart.sell.pojo.ProductInfo;
import com.heart.sell.service.OrderService;
import com.heart.sell.service.PayService;
import com.heart.sell.service.ProductService;
import com.heart.sell.service.PushMessage;
import com.heart.sell.util.UuidUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 默认订单实现
 *
 * @author Luo Zhen
 * @create 2019-04-23 16:16
 */
@Service
@Slf4j
public class DefaultOrderServiceImpl implements OrderService {

    @Autowired
    private OrderMasterMapper orderMasterMapper;
    @Autowired
    private ProductService productService;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UuidUtil uuidUtil;
    @Autowired
    private PayService payService;
    @Autowired
    private PushMessage pushMessage;
    @Autowired
    private WebSocket webSocket;

    @Override
    @Transactional(rollbackFor = SellException.class)
    public OrderDTO create(OrderDTO orderDTO) {
        String orderId = uuidUtil.getRandomUUID();

        BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);
        // 1.查询商品
        for (OrderDetail orderDetail : orderDTO.getOrderDetailList()) {
            ProductInfo productInfo = productService.findOne(orderDetail.getProductId());
            if (productInfo == null) {
                throw new SellException(ResponseCodeEnum.PRODUCT_NOT_EXIST);
            }

            // 2.计算订单总价
            orderAmount = productInfo.getProductPrice()
                    .multiply(new BigDecimal(orderDetail.getProductQuantity()))
                    .add(orderAmount);
            // 订单详情入库
            orderDetail.setDetailId(uuidUtil.getRandomUUID());
            orderDetail.setOrderId(orderId);

            BeanUtils.copyProperties(productInfo, orderDetail);
            orderDetailMapper.save(orderDetail);
        }
        // 3.写入订单数据库(orderDetail 和 orderMaster)
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setOrderId(orderId);
        BeanUtils.copyProperties(orderDTO, orderMaster);

        orderMaster.setOrderAmount(orderAmount);
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());

        orderMasterMapper.save(orderMaster);
        // 4.下单成功 扣掉库存
        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream()
                .map(e -> new CartDTO(e.getProductId(), e.getProductQuantity()))
                .collect(Collectors.toList());

        productService.decreaseStock(cartDTOList);

        // 发送webSocket消息
        webSocket.sendMessage(orderDTO.getOrderId());

        return orderDTO;
    }

    @Override
    public OrderDTO findOne(String orderId) {
        OrderMaster order = orderMasterMapper.findOne(orderId);
        if (order == null) {
            throw new SellException(ResponseCodeEnum.ORDER_NOT_EXIST);
        }

        List<OrderDetail> orderList = orderDetailMapper.findByOrderId(order.getOrderId());
        if (CollectionUtils.isEmpty(orderList)) {
            throw new SellException(ResponseCodeEnum.ORDER_DETAIL_NOT_EXIST);
        }

        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(order, orderDTO);
        orderDTO.setOrderDetailList(orderList);

        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findList(String buyerOpenid, Pageable pageable) {
        Page<OrderMaster> orderMasters = orderMasterMapper.findByBuyerOpenid(buyerOpenid, pageable);
        List<OrderDTO> orderDTOList = OrderMaster2OrderDTOConverter.convert(orderMasters.getContent());
        Page<OrderDTO> orderDTOPage = new PageImpl<OrderDTO>(orderDTOList, pageable, orderMasters.getTotalElements());
        return orderDTOPage;
    }

    @Override
    @Transactional(rollbackFor = SellException.class)
    public OrderDTO cancel(OrderDTO orderDTO) {
        // 判断订单状态
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.error("【取消订单】订单状态不正确,orderId={},orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResponseCodeEnum.ORDER_STATUS_ERROR);
        }

        // 修改订单状态
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setOrderStatus(OrderStatusEnum.CANCEL.getCode());

        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster updateResult = orderMasterMapper.save(orderMaster);
        if (updateResult == null) {
            log.error("【取消订单】更新失败,orderMaster={}", orderMaster);
            throw new SellException(ResponseCodeEnum.ORDER_UPDATE_FAIL);
        }

        // 返回库存
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
            log.error("【取消订单】订单中无商品详情，orderDTO={}", orderDTO);
            throw new SellException(ResponseCodeEnum.ORDER_DETAIL_EMPTY);
        }

        List<CartDTO> carDTOList = orderDTO.getOrderDetailList().stream()
                .map(e -> new CartDTO(e.getProductId(), e.getProductQuantity()))
                .collect(Collectors.toList());

        productService.increaseStock(carDTOList);
        // 如果已支付就要退款
        if (orderDTO.getPayStatus().equals(PayStatusEnum.SUCCESS.getCode())) {
            //todo
            payService.refund(orderDTO);
        }

        return orderDTO;
    }

    @Override
    @Transactional(rollbackFor = SellException.class)
    public OrderDTO finish(OrderDTO orderDTO) {
        // 判断订单状态
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.error("【完结订单】订单状态不正确,orderId={},orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResponseCodeEnum.ORDER_STATUS_ERROR);
        }

        // 修改订单状态
        orderDTO.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO, orderMaster);

        OrderMaster updateResult = orderMasterMapper.save(orderMaster);
        if (updateResult == null) {
            log.error("【完结订单】更新失败,orderMaster={}", orderMaster);
            throw new SellException(ResponseCodeEnum.ORDER_UPDATE_FAIL);
        }

        // 推送微信模板消息
        pushMessage.orderStatus(orderDTO);
        return orderDTO;
    }

    @Override
    @Transactional(rollbackFor = SellException.class)
    public OrderDTO paid(OrderDTO orderDTO) {
        // 判断订单状态
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.error("【订单支付完成】订单状态不正确,orderId={},orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResponseCodeEnum.ORDER_STATUS_ERROR);
        }

        // 判断支付状态
        if (!orderDTO.getPayStatus().equals(PayStatusEnum.WAIT.getCode())) {
            log.error("【订单支付完成】订单状态不正确,orderId={}", orderDTO);
            throw new SellException(ResponseCodeEnum.ORDER_STATUS_ERROR);
        }
        // 修改支付状态
        orderDTO.setPayStatus(PayStatusEnum.SUCCESS.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO, orderMaster);

        OrderMaster updateResult = orderMasterMapper.save(orderMaster);
        if (updateResult == null) {
            log.error("【订单支付完成】更新失败,orderMaster={}", orderMaster);
            throw new SellException(ResponseCodeEnum.ORDER_UPDATE_FAIL);
        }
        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findList(Pageable pageable) {
        Page<OrderMaster> orderMasterPage = orderMasterMapper.findAll(pageable);
        List<OrderDTO> orderDTOList = OrderMaster2OrderDTOConverter.convert(orderMasterPage.getContent());
        Page<OrderDTO> orderDTOPage = new PageImpl<OrderDTO>(orderDTOList, pageable, orderMasterPage.getTotalElements());
        return orderDTOPage;
    }
}
